﻿using System;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using VioletDevelopmentLaboratory.Net.Web.Component;

namespace VioletDevelopmentLaboratory.Net.Web.WebControls
{
	public enum BoardThreadSummaryMode { Normal, Thumbnail }

	public class ThreadSummaryTemplateContainer : Control, INamingContainer
	{
		private BoardThread currentThread;
		public BoardThread CurrentThread { get { return this.currentThread; } }

		internal ThreadSummaryTemplateContainer(BoardThread currentThread)
		{
			this.currentThread = currentThread;
		}
	}

	public class ThreadSummaryRowDataBoundEventArgs : EventArgs
	{
		public ThreadSummaryRowDataBoundEventArgs(ThreadSummaryTemplateContainer summaryTemplate)
		{
			this.row = summaryTemplate;
		}

		private ThreadSummaryTemplateContainer row;
		public ThreadSummaryTemplateContainer Row { get { return this.row; } }
	}

	public delegate void ThreadSummaryRowDataBoundEventHandler(Object sender, ThreadSummaryRowDataBoundEventArgs e);

	[ToolboxData("<{0}:BoardThreadSummary runat=server></{0}:BoardThreadSummary>"),
	ParseChildren(ChildrenAsProperties = true),
	Designer(typeof(VWebControlDesigner))]
	public class BoardThreadSummary : BoardSummaryBase
	{
		#region Behavior
		[Browsable(true),
		Category("Behavior"),
		DefaultValue("")]
		public String ComponentID { get { return ViewState["ComponentID"].ToString(); } set { ViewState["ComponentID"] = value; } }

		[Browsable(true),
		Category("Behavior"),
		DefaultValue("[{0}]&nbsp;")]
		public String CategoryNameFormat { get { return ViewState["CategoryNameFormat"].ToString(); } set { ViewState["CategoryNameFormat"] = value; } }

		[Browsable(true),
		Category("Behavior"),
		DefaultValue("&nbsp;+{0}")]
		public String CommentCountFormat { get { return ViewState["CommentCountFormat"].ToString(); } set { ViewState["CommentCountFormat"] = value; } }

		[Browsable(true),
		Category("Behavior"),
		DefaultValue("&nbsp;({0})")]
		public String ReadCountFormat { get { return ViewState["ReadCountFormat"].ToString(); } set { ViewState["ReadCountFormat"] = value; } }

		[Browsable(true),
		Category("Behavior"),
		TypeConverter(typeof(BoardThreadSummaryMode)),
		DefaultValue(BoardThreadSummaryMode.Normal)]
		public BoardThreadSummaryMode Mode { get { return (BoardThreadSummaryMode)ViewState["Mode"]; } set { ViewState["Mode"] = value; } }
		#endregion

		#region Appearance
		[Browsable(true),
		Category("Appearance"),
		DefaultValue(""),
		Editor(typeof(System.Web.UI.Design.UrlEditor), typeof(System.Drawing.Design.UITypeEditor)),
		UrlProperty]
		public string HeaderNavigateUrl { get { return ViewState["HeaderNavigateUrl"].ToString(); } set { ViewState["HeaderNavigateUrl"] = value; } }
		#endregion

		#region Stress
		[Browsable(true),
		Category("Appearance"),
		DefaultValue(""),
		Editor(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(System.Drawing.Design.UITypeEditor)),
		UrlProperty]
		public String NewImageUrl { get { return ViewState["NewImageUrl"].ToString(); } set { ViewState["NewImageUrl"] = value; } }

		[Browsable(true),
		Category("Appearance"),
		DefaultValue("New")]
		public String NewImageAlternateText { get { return ViewState["NewImageAlternateText"].ToString(); } set { ViewState["NewImageAlternateText"] = value; } }

		[Browsable(true),
		Category("Appearance"),
		DefaultValue(""),
		Editor(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(System.Drawing.Design.UITypeEditor)),
		UrlProperty]
		public String TodayImageUrl { get { return ViewState["TodayImageUrl"].ToString(); } set { ViewState["TodayImageUrl"] = value; } }

		[Browsable(true),
		Category("Appearance"),
		DefaultValue("Today")]
		public String TodayImageAlternateText { get { return ViewState["TodayImageAlternateText"].ToString(); } set { ViewState["TodayImageAlternateText"] = value; } }

		[Browsable(true),
		Category("Appearance"),
		DefaultValue(""),
		Editor(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(System.Drawing.Design.UITypeEditor)),
		UrlProperty]
		public String HotImageUrl { get { return ViewState["HotImageUrl"].ToString(); } set { ViewState["HotImageUrl"] = value; } }

		[Browsable(true),
		Category("Appearance"),
		DefaultValue("Hot")]
		public String HotImageAlternateText { get { return ViewState["HotImageAlternateText"].ToString(); } set { ViewState["HotImageAlternateText"] = value; } }

		[Browsable(true),
		Category("Appearance"),
		DefaultValue(""),
		Editor(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(System.Drawing.Design.UITypeEditor)),
		UrlProperty]
		public String SecretImageUrl { get { return ViewState["SecretImageUrl"].ToString(); } set { ViewState["SecretImageUrl"] = value; } }

		[Browsable(true),
		Category("Appearance"),
		DefaultValue("Secret")]
		public String SecretImageAlternateText { get { return ViewState["SecretImageAlternateText"].ToString(); } set { ViewState["SecretImageAlternateText"] = value; } }
		#endregion

		#region Template
		private ITemplate itemTemplate;
		[TemplateContainer(typeof(ThreadSummaryTemplateContainer)),
		PersistenceMode(PersistenceMode.InnerProperty),
		Browsable(false)]
		public ITemplate ItemTemplate { get { return this.itemTemplate; } set { this.itemTemplate = value; } }

		private ITemplate headerTemplate;
		[TemplateContainer(typeof(ThreadSummaryTemplateContainer)),
		PersistenceMode(PersistenceMode.InnerDefaultProperty),
		Browsable(false)]
		public ITemplate HeaderTemplate { get { return this.headerTemplate; } set { this.headerTemplate = value; } }

		private ITemplate footerTemplate;
		[TemplateContainer(typeof(ThreadSummaryTemplateContainer)),
		PersistenceMode(PersistenceMode.InnerDefaultProperty),
		Browsable(false)]
		public ITemplate FooterTemplate { get { return this.footerTemplate; } set { this.footerTemplate = value; } }
		#endregion

		#region Event
		[Category("Action")]
		public event ThreadSummaryRowDataBoundEventHandler RowDataBound;
		#endregion

		public BoardThreadSummary() : base()
		{
			this.ComponentID = "";
			this.HeaderNavigateUrl = "";

			this.Mode = BoardThreadSummaryMode.Normal;

			this.CategoryNameFormat = "";
			this.CommentCountFormat = "";
			this.ReadCountFormat = "";

			this.NewImageUrl = "";
			this.NewImageAlternateText = "";
			this.TodayImageUrl = "";
			this.TodayImageAlternateText = "";
			this.HotImageUrl = "";
			this.HotImageAlternateText = "";
			this.SecretImageUrl = "";
			this.SecretImageAlternateText = "";
		}

		protected override void CreateChildControls()
		{
			Board currentBoard = Board.GetBoard(this.ComponentID);

			if (currentBoard != null)
			{
				if (String.IsNullOrEmpty(this.HeaderText))
					this.HeaderText = currentBoard.Name;

				if(String.IsNullOrEmpty(this.HeaderNavigateUrl))
					this.HeaderNavigateUrl = currentBoard.PageUrl;
			}

			this.PageSize = VUtility.GetControlSetting(1, 100, this.PageSize, "BoardThreadSummary.PageSize", 5);
			this.ItemLength = VUtility.GetControlSetting(1, 100, this.ItemLength, "BoardThreadSummary.ItemLength", 15);
			this.DateFormat = VUtility.GetControlSetting(this.DateFormat, "BoardThreadSummary.DateFormat", "{0:d}&nbsp;");
			this.ReduceCharacter = VUtility.GetControlSetting(this.ReduceCharacter, "BoardThreadSummary.ReduceCharacter", "...");
			this.EmptyDataText = VUtility.GetControlSetting(this.EmptyDataText, "BoardThreadSummary.EmptyDataText", "No Data.");

			this.CssClass = VUtility.GetControlSetting(this.CssClass, "BoardThreadSummary.CssClass", "BoardThreadSummray_Default");

			this.FooterText = VUtility.GetControlSetting(this.FooterText, "BoardThreadSummary.FooterText", "");
			this.FooterImageUrl = VUtility.GetControlSetting(this.FooterImageUrl, "BoardThreadSummary.FooterImageUrl", "");

			this.CategoryNameFormat = VUtility.GetControlSetting(this.CategoryNameFormat, "BoardThreadSummary.CategoryNameFormat", "[{0}]&nbsp;");
			this.CommentCountFormat = VUtility.GetControlSetting(this.CommentCountFormat, "BoardThreadSummary.CommentCountFormat", "&nbsp;+{0}");
			this.ReadCountFormat = VUtility.GetControlSetting(this.ReadCountFormat, "BoardThreadSummary.ReadCountFormat", "&nbsp;({0})");

			this.NewImageUrl = VUtility.GetControlSetting(this.NewImageUrl, "BoardThreadSummary.NewImageUrl",
				Page.ClientScript.GetWebResourceUrl(this.GetType(), "VioletDevelopmentLaboratory.Net.Web.WebResources.stress_new_small.gif").Replace("&", "&amp;"));
			this.NewImageAlternateText = VUtility.GetControlSetting(this.NewImageAlternateText, "BoardThreadSummary.NewImageAlternateText", "New");
	
			this.TodayImageUrl = VUtility.GetControlSetting(this.TodayImageUrl, "BoardThreadSummary.TodayImageUrl",
				Page.ClientScript.GetWebResourceUrl(this.GetType(), "VioletDevelopmentLaboratory.Net.Web.WebResources.stress_today_small.gif").Replace("&", "&amp;"));
			this.TodayImageAlternateText = VUtility.GetControlSetting(this.TodayImageAlternateText, "BoardThreadSummary.TodayImageAlternateText", "Today");

			this.HotImageUrl = VUtility.GetControlSetting(this.HotImageUrl, "BoardThreadSummary.HotImageUrl",
				Page.ClientScript.GetWebResourceUrl(this.GetType(), "VioletDevelopmentLaboratory.Net.Web.WebResources.stress_hot_small.gif").Replace("&", "&amp;"));
			this.HotImageAlternateText = VUtility.GetControlSetting(this.HotImageAlternateText, "BoardThreadSummary.HotImageAlternateText", "Hot");
	
			this.SecretImageUrl = VUtility.GetControlSetting(this.SecretImageUrl, "BoardThreadSummary.SecretImageUrl",
				Page.ClientScript.GetWebResourceUrl(this.GetType(), "VioletDevelopmentLaboratory.Net.Web.WebResources.stress_hot_small.gif").Replace("&", "&amp;"));
			this.SecretImageAlternateText = VUtility.GetControlSetting(this.SecretImageAlternateText, "BoardThreadSummary.SecretImageAlternateText", "Secret");

			base.CreateChildControls();
		}

		protected override Control createHeader()
		{
			if (this.HeaderTemplate == null)
			{
				Literal header = new Literal();

				if (String.IsNullOrEmpty(this.HeaderImageUrl))
				{
					header.Text = String.Format("<div class=\"Header\"><a href=\"{0}\">{1}</a></div>",
						ResolveClientUrl(this.HeaderNavigateUrl),
						this.HeaderText);
				}
				else
				{
					header.Text = String.Format("<div class=\"Header\"><a href=\"{0}\"><img src=\"{1}\" alt=\"{2}\" /></a></div>",
						ResolveClientUrl(this.HeaderNavigateUrl),
						ResolveClientUrl(this.HeaderImageUrl),
						this.HeaderText);
				}

				return header;
			}
			else
			{
				ThreadSummaryTemplateContainer template = null;

				template = new ThreadSummaryTemplateContainer(null);
				template.EnableViewState = false;
				this.HeaderTemplate.InstantiateIn(template);

				return template;
			}
		}

		protected override Control createList()
		{
			Board currentBoard = Board.GetBoard(this.ComponentID);

			if (currentBoard != null)
			{
				BoardThreadCollection threadCollection = currentBoard.GetThreadSummayCollection(this.PageSize);

				if (threadCollection != null)
				{
					if (this.ItemTemplate != null)
					{
						#region Template
						Control items = new Control();
						items.EnableViewState = false;

						ThreadSummaryTemplateContainer template = null;
						ThreadSummaryRowDataBoundEventArgs args = null;

						foreach (BoardThread thread in threadCollection)
						{
							template = new ThreadSummaryTemplateContainer(thread);
							template.EnableViewState = false;
							this.ItemTemplate.InstantiateIn(template);
							template.DataBind();

							args = new ThreadSummaryRowDataBoundEventArgs(template);
							if (this.RowDataBound != null)
							{
								this.RowDataBound(this, args);
							}

							items.Controls.Add(template);
						}

						return items;
						#endregion
					}
					else
					{
						Literal items = new Literal();
						String liStringFormat = String.Empty;

						switch (this.Mode)
						{
							case BoardThreadSummaryMode.Normal:
								items.Text = "<ul>";

								#region Normal Mode
								liStringFormat = "<li>{0}{1}{2}{3}<span class=\"CommentCount\">{4}</span><span class=\"ReadCount\">{5}</span></li>";

								foreach (BoardThread thread in threadCollection)
								{
									#region Link
									String link = "<a href=\"{0}\">{1}</a>";
									String linkUrl = "";
									String linkText = "";
									if (!String.IsNullOrEmpty(currentBoard.PageUrl))
										linkUrl = thread.PageUrl.Replace("&", "&amp;");

									if (thread.Title.Length > this.ItemLength)
										linkText = Page.Server.HtmlEncode(Page.Server.HtmlDecode(thread.Title).Substring(0, ItemLength).Trim() + this.ReduceCharacter);
									else
										linkText = thread.Title;

									link = String.Format(link, linkUrl, linkText);
									#endregion

									#region Stress
									String image = "";
									String imageUrl = "";
									String imageText = "";
									//새글강조
									if (currentBoard.UseStressNew)
									{
										DateTime _now = DateTime.Now;
										TimeSpan _timeSpan = _now - thread.RegistrationDate;

										if (_timeSpan.TotalMinutes < 1440)
										{
											image = "&nbsp;<img src=\"{0}\" alt=\"{1}\" />";
											imageText = this.NewImageAlternateText;

											if (!String.IsNullOrEmpty(this.NewImageUrl))
												imageUrl = ResolveClientUrl(this.NewImageUrl);

											image = String.Format(image, imageUrl, imageText);
										}
									}
									//오늘글강조
									if (currentBoard.UseStressToday)
									{
										if (DateTime.Now.ToShortDateString() == thread.RegistrationDate.ToShortDateString())
										{
											image = "&nbsp;<img src=\"{0}\" alt=\"{1}\" />";
											imageText = this.TodayImageAlternateText;

											if (!String.IsNullOrEmpty(this.TodayImageUrl))
												imageUrl = ResolveClientUrl(this.TodayImageUrl);

											image = String.Format(image, imageUrl, imageText);
										}
									}
									//인기글강조
									if (currentBoard.UseStressHot)
									{
										if (thread.ReadCount > currentBoard.HotCount)
										{
											image = "&nbsp;<img src=\"{0}\" alt=\"{1}\" />";
											imageText = this.HotImageAlternateText;

											if (!String.IsNullOrEmpty(this.HotImageUrl))
												imageUrl = ResolveClientUrl(this.HotImageUrl);

											image = String.Format(image, imageUrl, imageText);
										}
									}
									//비밀글
									if (thread.IsSecret)
									{
										image = "&nbsp;<img src=\"{0}\" alt=\"{1}\" />";
										imageText = this.SecretImageAlternateText;

										if (!String.IsNullOrEmpty(this.SecretImageUrl))
											imageUrl = ResolveClientUrl(this.SecretImageUrl);

										image = String.Format(image, imageUrl, imageText);
									}
									#endregion

									items.Text += String.Format(liStringFormat,
										String.Format(this.DateFormat, thread.RegistrationDate),
										!String.IsNullOrEmpty(thread.CategoryName) ? String.Format("<span class=\"Category_{0}\">{1}</span>", thread.CategoryID, String.Format(this.CategoryNameFormat, thread.CategoryName)) : "",
										link,
										image,
										String.Format(this.CommentCountFormat, thread.CommentCount),
										String.Format(this.ReadCountFormat, thread.ReadCount));
								}
								items.Text += "</ul>";
								#endregion

								break;
							case BoardThreadSummaryMode.Thumbnail:

								#region Thumbnail Mode
								liStringFormat = "<div class=\"ThumbnailItem\"><div><img src=\"{0}\" alt=\"Thumbnail\" class=\"ThumbnailImage\" /></div><div>{1}</div><div>{2}<span class=\"CommentCount\">{3}</span><span class=\"ReadCount\">{4}</span></div><div>{5}</div></div>";

								foreach (BoardThread thread in threadCollection)
								{
									#region Thumbnail
									String thumbnailImageUrl = ResolveClientUrl("~/vboard/common/image/noimage.gif");

									if (!thread.IsSecret && !thread.IsBlocked)
									{
										AttachmentFileInfoCollection attachmentFileInfoCollection = currentBoard.GetAttachmentFileManager().GetAttachmentFileInfoCollection(thread.ThreadID);

										if (attachmentFileInfoCollection != null)
										{
											foreach (AttachmentFileInfo file in attachmentFileInfoCollection)
											{
												if (file.UploadFile.ContentType.IndexOf("image") > -1)
												{
													thumbnailImageUrl = BoardUtil.GetAttachmentThumbnailUrl(thread.ComponentID, file.FileID).Replace("&", "&amp;");
													break;
												}
											}
										}
									}
									#endregion

									#region Link
									String link = "<a href=\"{0}\">{1}</a>";
									String linkUrl = "";
									String linkText = "";
									if (!String.IsNullOrEmpty(currentBoard.PageUrl))
										linkUrl = thread.PageUrl.Replace("&", "&amp;");

									if (thread.Title.Length > this.ItemLength)
										linkText = Page.Server.HtmlEncode(Page.Server.HtmlDecode(thread.Title).Substring(0, ItemLength).Trim() + this.ReduceCharacter);
									else
										linkText = thread.Title;

									link = String.Format(link, linkUrl, linkText);
									#endregion

									#region Stress
									String image = "";
									String imageUrl = "";
									String imageText = "";
									//새글강조
									if (currentBoard.UseStressNew)
									{
										DateTime _now = DateTime.Now;
										TimeSpan _timeSpan = _now - thread.RegistrationDate;

										if (_timeSpan.TotalMinutes < 1440)
										{
											image = "<img src=\"{0}\" alt=\"{1}\" />";
											imageText = this.NewImageAlternateText;

											if (!String.IsNullOrEmpty(this.NewImageUrl))
												imageUrl = ResolveClientUrl(this.NewImageUrl);

											image = String.Format(image, imageUrl, imageText);
										}
									}
									//오늘글강조
									if (currentBoard.UseStressToday)
									{
										if (DateTime.Now.ToShortDateString() == thread.RegistrationDate.ToShortDateString())
										{
											image = "<img src=\"{0}\" alt=\"{1}\" />";
											imageText = this.TodayImageAlternateText;

											if (!String.IsNullOrEmpty(this.TodayImageUrl))
												imageUrl = ResolveClientUrl(this.TodayImageUrl);

											image = String.Format(image, imageUrl, imageText);
										}
									}
									//인기글강조
									if (currentBoard.UseStressHot)
									{
										if (thread.ReadCount > currentBoard.HotCount)
										{
											image = "<img src=\"{0}\" alt=\"{1}\" />";
											imageText = this.HotImageAlternateText;

											if (!String.IsNullOrEmpty(this.HotImageUrl))
												imageUrl = ResolveClientUrl(this.HotImageUrl);

											image = String.Format(image, imageUrl, imageText);
										}
									}
									//비밀글
									if (thread.IsSecret)
									{
										image = "<img src=\"{0}\" alt=\"{1}\" />";
										imageText = this.SecretImageAlternateText;

										if (!String.IsNullOrEmpty(this.SecretImageUrl))
											imageUrl = ResolveClientUrl(this.SecretImageUrl);

										image = String.Format(image, imageUrl, imageText);
									}
									#endregion

									items.Text += String.Format(liStringFormat,
										thumbnailImageUrl,
										link,
										image,
										String.Format(this.CommentCountFormat, thread.CommentCount),
										String.Format(this.ReadCountFormat, thread.ReadCount),
										String.Format(this.DateFormat, thread.RegistrationDate)
									);
								}

								items.Text += "<div style=\"clear : both;\"></div>";
								#endregion

								break;
						}

						return items;
					}
				}
			}

			Literal emptyControl = new Literal();
			emptyControl.EnableViewState = false;
			emptyControl.Text = String.Format("<div class=\"Empty\">{0}</div>", this.EmptyDataText);

			return emptyControl;
		}

		protected override Control createFooter()
		{
			if (this.FooterTemplate == null)
			{
				Literal div = new Literal();

				if (String.IsNullOrEmpty(this.FooterImageUrl))
				{
					div.Text = String.Format("<div class=\"Footer\">{0}</div>", this.FooterText);
				}
				else
				{
					div.Text = String.Format("<div class=\"Footer\"><img src=\"{0}\" alt=\"{1}\" /></div>",
						ResolveClientUrl(this.FooterImageUrl),
						this.FooterText);
				}

				return div;
			}
			else
			{
				ThreadSummaryTemplateContainer template = null;

				template = new ThreadSummaryTemplateContainer(null);
				template.EnableViewState = false;
				this.FooterTemplate.InstantiateIn(template);

				return template;
			}
		}
	}
}
